﻿using AssistCore;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Configuration;
using System.Collections.Generic;

namespace Helper
{
    public partial class FishingHelper : CCWin.Skin_Mac
    {
        public FishingHelper()
        {
            InitializeComponent();
            this.Icon = Properties.HelpResource.app;
        }
        private int fishCount = 0;
        private Thread fishingThread;
        private int startFishKey = int.Parse(ConfigurationManager.AppSettings["StartFishKey"]),
            stopFishKey = int.Parse(ConfigurationManager.AppSettings["StopFishKey"]);
        private int matchType, similar = 0;
        private DateTime startTime = DateTime.Now.AddDays(1);
        private IntPtr gameHwnd = IntPtr.Zero;
        private void btn_start_Click(object sender, EventArgs e)
        {

            if (fishingThread != null && fishingThread.IsAlive)
            {
                fishingThread.Abort();
                this.AddLog("停止操作!");
                btn_start.Text = "开始钓鱼(Home)";
                groupBox1.Enabled = true;
                groupBox2.Enabled = true;
            }
            else
            {
                this.AddLog("准备开始钓鱼!");
                matchType = int.Parse(cb_mode.SelectedValue.ToString());
                similar = int.Parse(cb_similar.SelectedValue.ToString());
                if (rdb_gang.Checked)
                {
                    fishingThread = new Thread(StartGangFishing);
                    fishingThread.Start();
                }
                else if (rdb_dbf.Checked)
                {
                    fishingThread = new Thread(StartDBFFishing);
                    fishingThread.Start();
                }
                else if (rdb_field.Checked)
                {
                    fishingThread = new Thread(StartFieldFishing);
                    fishingThread.Start();
                }
                btn_start.Text = "停止钓鱼(Home)";
                groupBox1.Enabled = false;
                groupBox2.Enabled = false;
            }
        }

        private void FishingHelper_Shown(object sender, EventArgs e)
        {
            Win32Core.RegisterHotKey(this.Handle, 100, 0, (int)Keys.Home);
            var modeDataScoure = new List<object>();
            modeDataScoure.Add(new
            {
                Name = "模式一",
                Value = 1
            });
            modeDataScoure.Add(new
            {
                Name = "模式二",
                Value = 3
            });
            modeDataScoure.Add(new
            {
                Name = "模式三",
                Value = 5
            });
            cb_mode.DataSource = modeDataScoure;
            cb_mode.DisplayMember = "Name";
            cb_mode.ValueMember = "Value";

            var similarDataScoure = new List<object>();
            similarDataScoure.Add(new
            {
                Name = "低",
                Value = 1
            });
            similarDataScoure.Add(new
            {
                Name = "中",
                Value = 2
            });
            similarDataScoure.Add(new
            {
                Name = "高",
                Value = 3
            });
            cb_similar.DataSource = similarDataScoure;
            cb_similar.DisplayMember = "Name";
            cb_similar.ValueMember = "Value";
            cb_mode.SelectedIndex = Properties.HelperSettings.Default.fishModel;
            cb_similar.SelectedIndex = Properties.HelperSettings.Default.fishSimilar;
            switch (Properties.HelperSettings.Default.fishType)
            {
                case 0:
                    {
                        rdb_gang.Checked = true;
                        rdb_dbf.Checked = false;
                        rdb_field.Checked = false;
                        break;
                    }
                case 1:
                    {
                        rdb_gang.Checked = false;
                        rdb_dbf.Checked = true;
                        rdb_field.Checked = false;
                        break;
                    }

                case 2:
                    {
                        rdb_gang.Checked = false;
                        rdb_dbf.Checked = false;
                        rdb_field.Checked = true;
                        break;
                    }
            }
        }

        private void FishingHelper_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (fishingThread != null && fishingThread.IsAlive)
            {
                fishingThread.Abort();
            }
            Win32Core.UnregisterHotKey(this.Handle, 100);
            Properties.HelperSettings.Default.fishModel = cb_mode.SelectedIndex;
            Properties.HelperSettings.Default.fishSimilar = cb_mode.SelectedIndex;
            Properties.HelperSettings.Default.fishType = rdb_gang.Checked ? 0 : rdb_dbf.Checked ? 1 : 2;
            Properties.HelperSettings.Default.Save();
        }
        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    HandleHotkey(m);
                    break;
            }
            base.WndProc(ref m);
        }
        private void HandleHotkey(Message m)
        {
            switch (m.WParam.ToInt32())
            {
                case 100:
                    {
                        btn_start.PerformClick();
                        break;
                    }
            }
        }

        private void StartGangFishing()
        {
            var handle = Win32Core.GetForegroundWindow();
            Rect rect;
            Win32Core.GetWindowRect(handle, out rect);
            var pCursor = new Point();
            Win32Core.GetCursorPos(out pCursor);
            gameHwnd = Win32Core.WindowFromPoint(pCursor);
            while (true)
            {
                //每钓鱼20次使用一次体力药水
                if (fishCount > 20)
                {
                    GameAction.OpenBag(CDD.DDContext, matchType, similar);
                    Thread.Sleep(1000);
                    GameAction.UseProp(CDD.DDContext, Properties.HelpResource.tili, 1000 * 11, matchType, similar);
                    fishCount = 0;
                }
                var pos = GameAction.FindPropPositon(Properties.HelpResource.fishing_state, matchType, similar);
                if (!pos.HasValue)
                {

                    this.AddLog("已退出钓鱼模式，自动按互动键");
                    Win32Core.SetForegroundWindow(gameHwnd);
                    CDD.DDContext.key((int)KeyCodeMap.KeysToDD(Keys.F), 1);
                    CDD.DDContext.key((int)KeyCodeMap.KeysToDD(Keys.F), 2);
                }
                Win32Core.SetForegroundWindow(gameHwnd);
                /*按下开始钓鱼键，然后等待1s后开始截屏*/
                CDD.DDContext.key(startFishKey, 1);
                CDD.DDContext.key(startFishKey, 2);
                this.AddLog("挥杆钓鱼");
                startTime = DateTime.Now;
                Thread.Sleep(1000);

                bool bingo = false;
                do
                {
                    Bitmap bp = new Bitmap(rect.Right - rect.Left, rect.Bottom - rect.Top);
                    var g = Graphics.FromImage(bp);
                    g.CopyFromScreen(0, 0, 0, 0, bp.Size);
                    using (MemoryStream msSource = new MemoryStream())
                    {
                        bp.Save(msSource, ImageFormat.Png);

                        var fishBingo = Properties.HelpResource.fishBingo;
                        using (MemoryStream msTarget = new MemoryStream())
                        {
                            fishBingo.Save(msTarget, ImageFormat.Png);
                            var p = ImageCore.MatchTemplate(msSource.ToArray(), msTarget.ToArray(), matchType, similar);
                            if (p.HasValue)
                            {
                                bingo = true;
                                Win32Core.SetForegroundWindow(gameHwnd);
                                Thread.Sleep(200);
                                CDD.DDContext.key(stopFishKey, 1);
                                CDD.DDContext.key(stopFishKey, 2);
                                this.AddLog("已上钩,手杆并等待下一次挥杆");
                                Thread.Sleep(4000);
                            }

                            if ((DateTime.Now - startTime).TotalSeconds > 30)
                            {
                                this.AddLog("30秒内没有上钩，重新挥杆");
                                bingo = true;
                            }
                            else
                            {
                                this.AddLog("未检测到上钩,继续等待");
                                Thread.Sleep(1000);
                            }
                        }

                    }
                } while (!bingo);
            }
        }
        private void StartDBFFishing() { }
        private void StartFieldFishing() { }
        private void AddLog(string message)
        {
            Action action = () =>
            {
                rtb_log.AppendText(string.Format("[{0}]{1}{2}", DateTime.Now.ToString("mm:ss"), message, Environment.NewLine));
                rtb_log.SelectionStart = rtb_log.Text.Length;
                rtb_log.ScrollToCaret();
            };
            if (rtb_log.InvokeRequired)
            {
                rtb_log.Invoke(action);
            }
            else
            {
                action();
            }
        }
    }
}
